<template>
  <div class="app-container">

    <!-- 主地图容器 - 新增这部分 -->
    <div class="map-container" v-show="false">
      <div id="mainMapContainer" class="main-map"></div>
    </div>




    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="社区" prop="communityId">
        <el-select v-model="queryParams.communityId" placeholder="请选择社区ID" clearable style="width: 200px">
          <el-option label="阳光花园" value="1"></el-option>
          <el-option label="山水名都" value="3"></el-option>
          <el-option label="枫林壹号" value="4"></el-option>
          <el-option label="湖园家园" value="5"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="楼宇ID" prop="buildingId">
        <el-input
          v-model="queryParams.buildingId"
          placeholder="请输入楼宇编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单元数" prop="unitNo">
        <el-input
          v-model="queryParams.unitNo"
          placeholder="请输入单元数"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="巡更点名称" prop="pointName" label-width="128px">
        <el-input
          v-model="queryParams.pointName"
          placeholder="请输入巡更点名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="位置编号" prop="positionNo">
        <el-input
          v-model="queryParams.positionNo"
          placeholder="请输入位置编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="纬度" prop="latitude">
        <el-input
          v-model="queryParams.latitude"
          placeholder="请输入纬度"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="经度" prop="longitude">
        <el-input
          v-model="queryParams.longitude"
          placeholder="请输入经度"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="拍照要求" prop="photoRequirement">
        <el-input
          v-model="queryParams.photoRequirement"
          placeholder="请输入拍照要求"
          clearable
          @keyup.enter="handleQuery"
        />

      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" align="center">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:point:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:point:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:point:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:point:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="pointList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="巡更点ID" align="center" prop="patrolPointId" />
      <el-table-column label="社区" align="center" prop="communityId" :formatter="formatCommunityName" />
      <el-table-column label="楼宇ID" align="center" prop="buildingId" />
      <el-table-column label="单元数" align="center" prop="unitNo" />
      <el-table-column label="巡更点名称" align="center" prop="pointName" />
      <el-table-column label="位置编号" align="center" prop="positionNo" />
      <el-table-column label="纬度" align="center" prop="latitude" />
      <el-table-column label="经度" align="center" prop="longitude" />
      <el-table-column label="拍照要求" align="center" prop="photoRequirement" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="描述" align="center" prop="description" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:point:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:point:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改point对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="pointRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="社区ID" prop="communityId">
          <el-input v-model="form.communityId" placeholder="请输入社区ID" />
        </el-form-item>
        <el-form-item label="楼宇ID" prop="buildingId">
          <el-input v-model="form.buildingId" placeholder="请输入楼宇ID" />
        </el-form-item>
        <el-form-item label="单元数" prop="unitNo">
          <el-input v-model="form.unitNo" placeholder="请输入单元数" />
        </el-form-item>
        <el-form-item label="巡更点名称" prop="pointName">
          <el-input v-model="form.pointName" placeholder="请输入巡更点名称" />
        </el-form-item>
        <el-form-item label="位置编号" prop="positionNo">
          <el-input v-model="form.positionNo" placeholder="请输入位置编号" />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="form.latitude" placeholder="请输入纬度" />
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input v-model="form.longitude" placeholder="请输入经度" />
        </el-form-item>


        <el-button class="control-btn" type="primary" @click="dialogVisible = true">
          打开地图
        </el-button>


        <el-form-item label="拍照要求" prop="photoRequirement">
          <el-input v-model="form.photoRequirement" placeholder="请输入拍照要求" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 地图选择弹窗 -->
    <el-dialog
        title="选择位置"
        v-model="dialogVisible"
        width="60%"
        :before-close="handleDialogClose"
        @open="handleMapDialogOpen"
    >
      <div id="dialogMapContainer" class="dialog-map"></div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="confirmMapSelection">确认选择</el-button>
        </div>
      </template>
    </el-dialog>
    </div>
</template>

<script setup name="Point">
import { listPoint, getPoint, delPoint, addPoint, updatePoint } from "@/api/system/point"
import { ref, reactive, toRefs, onMounted, onUnmounted,nextTick } from "vue"

const { proxy } = getCurrentInstance()

const pointList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

//地图弹窗
const dialogVisible = ref(false)
const mainMap= ref(null)
const dialogMap  = ref(null)



// 地图弹窗相关变量
const selectedPoint = ref(null)


const communityDict = {
  1: '阳光花园',
  2: '绿城雅苑',
  3: '山水名都',
  4: '枫林壹号',
  5: '湖畔家园'
};

// 单独定义格式化方法（与其他方法同级）
const formatCommunityName = (row) => {
  // 注意：row.communityId 可能是字符串类型，需转数字匹配字典键
  return communityDict[Number(row.communityId)] || row.communityId;
};

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    communityId: null,
    buildingId: null,
    unitNo: null,
    pointName: null,
    positionNo: null,
    latitude: null,
    longitude: null,
    photoRequirement: null,
    status: null,
    description: null,
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询point列表 */
function getList() {
  loading.value = true
  listPoint(queryParams.value).then(response => {
    pointList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    patrolPointId: null,
    communityId: null,
    buildingId: null,
    unitNo: null,
    pointName: null,
    positionNo: null,
    latitude: null,
    longitude: null,
    photoRequirement: null,
    status: null,
    description: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("pointRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.patrolPointId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加point"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _patrolPointId = row.patrolPointId || ids.value
  getPoint(_patrolPointId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改point"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["pointRef"].validate(valid => {
    if (valid) {
      if (form.value.patrolPointId != null) {
        updatePoint(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addPoint(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _patrolPointIds = row.patrolPointId || ids.value
  proxy.$modal.confirm('是否确认删除point编号为"' + _patrolPointIds + '"的数据项？').then(function() {
    return delPoint(_patrolPointIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/point/export', {
    ...queryParams.value
  }, `point_${new Date().getTime()}.xlsx`)
}


// 添加弹窗打开处理函数
async function handleMapDialogOpen() {
  try {
    // 每次打开弹窗时重新初始化地图
    await nextTick()
    await initDialogMap()
  } catch (error) {
    console.error('打开地图弹窗失败:', error)
    proxy.$message.error('地图加载失败，请稍后重试')
  }
}

// 组件挂载时初始化地图
onMounted(async () => {
  await nextTick()
  await initMainMap()
})

// 初始化主地图
async function initMainMap() {
  try {
    // 检查地图容器是否存在
    const mapContainer = document.getElementById('mainMapContainer')
    if (!mapContainer) {
      console.error('主地图容器不存在')
      return
    }

    // 检查百度地图API是否加载成功
    if (!window.BMapGL) {
      console.error('百度地图API未加载')
      proxy.$message.error('百度地图API加载失败，请刷新页面重试')
      return
    }

    // 创建地图实例
    mainMap.value = new BMapGL.Map('mainMapContainer')
    mainMap.value.centerAndZoom(new BMapGL.Point(116.404, 39.928), 15)
    mainMap.value.enableScrollWheelZoom(true)

    // 主地图点击事件
    mainMap.value.addEventListener('click', (e) => {
      proxy.$message.success(`主地图点击位置经纬度：${e.latlng.lng}, ${e.latlng.lat}`)
    })

    // 加载巡更点数据并在地图上显示
    await loadPatrolPoints()
  } catch (error) {
    console.error('初始化主地图失败:', error)
    proxy.$message.error('地图初始化失败，请稍后重试')
  }
}

// 初始化弹窗地图
async function initDialogMap() {
  try {
    // 确保DOM已更新
    await nextTick()

    // 检查地图容器是否存在
    const dialogMapContainer = document.getElementById('dialogMapContainer')
    if (!dialogMapContainer) {
      console.error('弹窗地图容器不存在')
      return
    }

    // 检查百度地图API是否加载成功
    if (!window.BMapGL) {
      console.error('百度地图API未加载')
      proxy.$message.error('百度地图API加载失败，请刷新页面重试')
      return
    }

    // 创建地图实例
    dialogMap.value = new BMapGL.Map('dialogMapContainer')
    dialogMap.value.centerAndZoom(new BMapGL.Point(116.404, 39.928), 15)
    dialogMap.value.enableScrollWheelZoom(true)

    // 弹窗地图点击事件
    dialogMap.value.addEventListener('click', (e) => {
      // 清除之前的标记
      dialogMap.value.clearOverlays()

      // 创建新标记
      const marker = new BMapGL.Marker(e.latlng)
      dialogMap.value.addOverlay(marker)

      // 保存选中的点
      selectedPoint.value = e.latlng

      proxy.$message.success(`已选择位置：经度${e.latlng.lng.toFixed(6)}，纬度${e.latlng.lat.toFixed(6)}`)
    })
    // 如果表单中已有经纬度，在地图上显示该位置
    if (form.value.latitude && form.value.longitude) {
      const point = new BMapGL.Point(Number(form.value.longitude), Number(form.value.latitude))
      dialogMap.value.centerAndZoom(point, 16)

      // 在该位置添加标记
      const marker = new BMapGL.Marker(point)
      dialogMap.value.addOverlay(marker)
      selectedPoint.value = point
    }
  } catch (error) {
    console.error('初始化弹窗地图失败:', error)
    proxy.$message.error('地图初始化失败，请稍后重试')
  }
}

// 加载巡更点数据并在地图上显示
async function loadPatrolPoints() {
  try {
    const res = await listPoint(queryParams.value)
    const points = res.rows || []

    // 清除现有标记
    if (mainMap.value) {
      mainMap.value.clearOverlays()
    }

    // 添加新标记
    points.forEach(point => {
      if (point.longitude && point.latitude) {
        const pointObj = new BMapGL.Point(point.longitude, point.latitude)
        const marker = new BMapGL.Marker(pointObj)

        // 添加信息窗口
        const infoWindow = new BMapGL.InfoWindow(
            `<div style="font-size:14px;">${point.pointName || '未命名巡更点'}</div><div>经度：${point.longitude}</div><div>纬度：${point.latitude}</div>`
        )
        // 点击事件：打开信息窗口 点击标记时弹出信息窗口
        marker.addEventListener('click', function() {
          this.openInfoWindow(infoWindow)
        })

        if (mainMap.value) {
          mainMap.value.addOverlay(marker)
        }
      }
    })
  } catch (error) {
    console.error('加载巡更点数据失败:', error)
  }
}

// 确认地图选择
function confirmMapSelection() {
  if (selectedPoint.value) {
    // 将选中的经纬度设置到表单中
    form.value.longitude = selectedPoint.value.lng.toFixed(6)
    form.value.latitude = selectedPoint.value.lat.toFixed(6)

    proxy.$message.success('位置选择成功')
    dialogVisible.value = false
  } else {
    proxy.$message.warning('请先在地图上选择一个位置')
  }
}

// 弹窗关闭处理
function handleDialogClose() {
  dialogVisible.value = false
  // 可以在这里添加清理逻辑
}

getList()
</script>

<style>
/* 地图容器样式 */
.main-map {
  width: 100%;
  height: 400px;
  margin-bottom: 20px;
  border: 1px solid #e6e6e6;
}

.dialog-map {
  width: 100%;
  height: 400px;
}

/* 控制按钮样式 */
.control-btn {
  margin-bottom: 15px;
}
</style>